<template>
    <div class="sifter-box flex-row-center" v-if="isEdit==0">
        <el-form :inline="true" :model="sifterForm" class="demo-form-inline">
            <el-form-item label="筛选：">
                <el-input v-model="sifterForm.key" placeholder="输入课程关键字" @input="proxy.$utils.debounce(updalist,sifterForm)"></el-input>
            </el-form-item>
            <el-form-item prop="type">
                <el-select style="width:120px;" v-model="sifterForm.type" placeholder="请选择" clearable @change="(e)=>{typeChange(e,'type')}">
                    <el-option v-for="item in globalData.trainTypeAry" :key="item.value" :label="item.text" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="issign">
                <el-select style="width:120px;" v-model="sifterForm.issign" placeholder="请选择" clearable @change="(e)=>{typeChange(e,'issign')}">
                    <el-option v-for="item in globalData.issignTypeAry" :key="item.value" :label="item.text" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker style="width:200px;" v-model="sifterForm.time" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" size="small" @change="datePickerChange" @clear="datePickerChange"></el-date-picker>
            </el-form-item>
        </el-form>
        <div></div>
    </div>

    <div class="listDiv" v-if="isEdit==0">
        <div class="el-table flex-row al-flex-start wrap pl20 pt20" style="align-content:flex-start;min-height:700px;">
            <div v-for="(v,i) in list" :key="i" class="flex-column mb20 mr15" style="height:180px;">
                <el-image style="width: 200px; height: 110px" class="pointer" @click="editData(v)" fit="cover" :src="fileurl+ '/train/'+ v.cover">
                        <template #error>
                            <div class="image-slot">
                                <el-image src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"/>
                            </div>
                        </template>
                    </el-image>
                <div class="base-size weight mt5 lineTwo flex-row-center">
                    <span class="lineTwo" style="width: 200px;">{{v.name||'暂无视频名称'}}</span>
                    <span :class="[`state-btn-${v.type==0?'primary':'warning'}`]">{{v.type==0?'线上':'线下'}}</span>
                    <span :class="[`state-btn-${obj.verify_states[v.verify_state].color}`,'ml10']">{{obj.verify_states[v.verify_state].t||''}}</span>
                    <span v-if="v.complete==1" class="state-btn-success">已完成</span>
                </div>
                <div class="mini-gray-size mt5 lineTwo" v-if="v.type==1">{{v.starttime.substring(0,10)||''}} ~ {{v.endtime.substring(0,10)||''}}</div>
            </div>
        </div>
        <div class="pd20 w100 flex-row-center ju-flex-end">
            <el-pagination
                v-model:currentPage="sifterForm.currentpage"
                v-model:page-size="sifterForm.pagesize"
                :page-sizes="[10, 20, 50, 100]" :total="total"
                @size-change="()=>{updalist()}"
                @current-change="()=>{updalist()}"
                layout="total, sizes, prev, pager, next, jumper"  background/>
        </div>
    </div>

    <div class="edit-box" v-if="isEdit!=0">
        <div class="title-box flex-row-center">
            <span class="pointer return flex-row-center mr10" @click="re_turn"><el-icon><back /></el-icon></span>
            <span class="flex1 lineOne mr10">课程详情</span>
            <span class="pointer base-size base-color" @click="chart">去咨询</span>
        </div>
        <div class="form-box">
            <div class="video-box flex-row">
                <!-- 线上视频及封面 -->
                <vue3VideoPlay :key="videokey" v-bind="videoOptions" :speed="speed" poster="" v-if="detail.videojson.length>0&&detail.complete!=''&&detail.verify_state=='1'&&detail.type==0"
                    @play="playvideo" @timeupdate="onTimeupdate" @loadedmetadata="loadedmetadata"/>
                <el-image v-if="(detail.videojson.length==0||!detail.videojson||detail.complete==''||detail.verify_state=='0')&&detail.type==0" style="width: 896px; height: 415px" fit="cover" :src="fileurl+ '/train/'+ detail.cover">
                    <template #error>
                        <div class="image-slot">
                            <el-image style="width: 896px; height: 415px" fit="cover" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"/>
                        </div>
                    </template>
                </el-image>
                <!-- 线上右侧视频栏目 -->
                <div class="videos-tab flex-column pd10-row" v-if="detail.videojson.length>0&&detail.complete!=''&&detail.verify_state=='1'&&detail.type==0">
                    <div 
                        :class="['tab','mt10','pd10','pointer',tabidx==i?'tab-active':'']"
                        v-for="(v,i) in detail.videojson" :key="i" @click="tabclick(i,v)">
                        <span class="lineTwo">{{v.name||'暂无视频名称'}}</span>
                        <span v-if="(studyform.study&&studyform.study[i].studytime!=0&&studyform.study[i].alltime!=0&&studyform.study[i].studytime==studyform.study[i].alltime)" class="state-btn-success">已看完</span>
                        <span v-else class="mini-size mt5 mb5">{{((v.videotime||0)/3600).toFixed(2)}}h / {{((studyform.study[i].studytime||0)/3600).toFixed(2)}}h</span>
                    </div>
                </div>
                <!-- 线下封面 -->
                <el-image v-if="detail.type==1" style="width: 896px; height: 415px" fit="cover" :src="fileurl+ '/train/'+ detail.cover">
                    <template #error>
                        <div class="image-slot">
                            <el-image style="width: 896px; height: 415px" fit="cover" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"/>
                        </div>
                    </template>
                </el-image>
                <!-- 审核取消报名 -->
                <div class="sign-box flex-center" v-if="(detail.complete==''||detail.verify_state=='0')">
                    <div v-if="detail.complete==''" class="sign base flex-center pointer" @click="sign(detail.train_id)">现在报名</div>
                    <div v-if="detail.verify_state=='0'" class="sign base flex-center pointer">审核中...</div>
                </div>
            </div>
            <!-- 线上附件栏目 -->
            <div v-if="detail.filejson.length>0&&detail.verify_state=='1'&&detail.type==0" class="mt10 pd20-row pt20 pb10 mini-gray-bg radius4 flex-column">
                <a v-for="(v,i) in detail.filejson" :key="i" :href="obj.fileurl+ '/train/'+ v.file" target="_bl_blank" class="flex-cloumn-center mb10">
                {{v.name||'暂无名称'}}.{{v.file.split('.')[1]}}<a class="base-color mini-size ml10">下载附件</a>
                </a>
            </div>
            <div class="flex-row head-box mt10">
                <div class="flex-column" style="flex:1;">
                    <div class="large-size weight mb10 ml10">
                        {{detail.name||''}}
                        <span :class="[`state-btn-${detail.type==0?'primary':'warning'}`,'ml10']">{{detail.type==0?'线上':'线下'}}</span>
                        <span v-if="detail.complete==1&&detail.type==0" class="state-btn-success">已完成</span>
                    </div>
                    <div class="flex-row-center ju-flex-start mt10 mb10 ml10 base-gray-size">
                        <span class="base-size mr20">课程数：{{detail.classhour||''}}</span>
                        <span class="base-size mr20">总课时：{{((studyform.alltime||0)/3600).toFixed(2)}}h</span>
                        <span class="base-size mr20">已完成课时：{{((studyform.studytime||0)/3600).toFixed(2)}}h</span>
                        <span class="base-size mr10">报名企业数：{{detail.companyCou}}人</span>
                        <!-- <span class="base-size mr10 flex-row-center">开课时间：{{detail.starttime.substring(0,10)||''}} ~ {{detail.endtime.substring(0,10)||''}}</span> -->
                    </div>
                </div>
                <div v-if="detail.verify_state!=1" :class="['cancel', 'flex-center', 'pointer', detail.complete!=''?'btn-gray':'btn-primary']" @click="sign(detail.train_id)">{{detail.complete!=''?'取消报名':'现在报名'}}</div>
            </div>
            <div class="line mb20"></div>
            <div v-html="detail.msg" class="mt20 v-html"></div>
        </div>
    </div>

</template>

<script setup>
    import { reactive,ref,getCurrentInstance,toRefs,toRaw,watch } from 'vue'
    import { Back,Edit,Delete,Timer,Phone,User } from '@element-plus/icons-vue'
    let { proxy } = getCurrentInstance()
    let obj = reactive({
        fileurl: proxy.$setting.globalUrl.fileurl,
        isEdit: 0,
        total: 0,
        list:[],
        sifterForm: {
            key: '',
            type: '',
            "issign":"",
            "time": "",
            "starttime":"",
            "endtime":"",
            currentpage: 1,
            pagesize: 10
        },
        detail: {},
        tabidx: 0,
        videoOptions: {
            width: "736px", //播放器高度
            height: "415px", //播放器高度
            color: "#409eff", //主题色
            title: "", //视频名称
            src: "https://cdn.jsdelivr.net/gh/xdlumia/files/video-play/IronMan.mp4", //视频源
            muted: false, //静音
            webFullScreen: false,
            speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
            // speed: true, //关闭进度条拖动
            autoPlay: false, //自动播放
            loop: false, //循环播放
            mirror: false, //镜像画面
            ligthOff: false, //关灯模式
            volume: 1, //默认音量大小
            control: true, //是否显示控制
            controlBtns: [
                "audioTrack",
                "quality",
                "speedRate",
                "volume",
                "setting",
                "pip",
                "pageFullScreen",
                "fullScreen",
            ], //显示所有按钮,
        },
        speed: false,
        videokey: 9999,
        isupdata: true,
        studyform:{
            train_id: '',
            study: [],
            alltime: 0,
            studytime: 0
        },
        verify_states: {
            '':{t:'未报名',color: 'warning'},
            '0':{t:'审核中',color: 'primary'},
            '1':{t:'通过',color: 'success'},
            '2':{t:'未通过',color: 'danger'}
        }
    });

    
    watch(
        () => obj.tabidx,
        (val) => {
            speed.value = studyform.value.study[val].isstudy
            videokey.value = (Math.random() * 100000).toFixed(0)
        }
    )

    const typeChange = (e,key)=>{
        if(e){
            sifterForm.value[key] = e
            updalist(obj.sifterForm)
        }else{
            sifterForm.value[key] = ''
            updalist(obj.sifterForm)
        }
    }
    
    const datePickerChange = (e)=>{
        console.log(e);
        
        sifterForm.value.starttime = e?e[0]:''
        sifterForm.value.endtime = e?e[1]:''
        updalist(sifterForm.value)
    }

    const updalist = (form)=>{
        let param = {
            ...obj.sifterForm,
            ...form
        }
        proxy.$ajax({url: 'train/list',data: param,bfLoading: true}).then(d => {
            console.log(d);
            if(d.success){
                total.value = d.msg.count||0
                list.value = d.msg.list;
            }else{}
        }).catch(e => {
            console.log(e)
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }
    updalist();

    const re_turn = ()=>{
        isEdit.value = 0;
    }

    const tabclick = (i,row)=>{
        tabidx.value = i
        videoOptions.value.src = fileurl.value+ '/train/'+ row.file
        console.log(videoOptions.value.src);
    }

    const editData = (item)=>{
        if(item){
            detail.value = item
            detail.value.videojson = typeof detail.value.videojson =='object'?detail.value.videojson:[];
            if(item.type==0&&detail.value.videojson&&detail.value.videojson.length>0){
                videoOptions.value.src = fileurl.value+ '/train/'+ detail.value.videojson[0].file
                tabidx.value= 0
            }
            // 更新学习情况
            studyform.value.train_id = item.train_id
            if(detail.value.type==0&&detail.value.videojson.length>0){//线上
                studyform.value.study = [];
                let alltime = 0;
                let studytime = 0;
                if(!detail.value.study||detail.value.study.length==0){
                    detail.value.videojson.map((e,i)=>{
                        const o = {
                            video: e.file,
                            studytime: 0,
                            alltime: 0,
                            isstudy: false
                        }
                        studyform.value.study.push(o);
                        alltime += +e.videotime||0;
                    })
                }else{
                    detail.value.videojson.map((e,i)=>{
                        if(!detail.value.study[i]){
                            studyform.value.study[i] = {
                                video: e.file,
                                studytime: 0,
                                alltime: 0,
                                isstudy: false
                            }
                        }else{
                            studyform.value.study[i] = detail.value.study[i];
                        }
                        alltime += +e.videotime||0;
                    })
                }
                studyform.value.study.map(e=>{
                    e.isstudy = e.studytime>0&&e.studytime==e.alltime
                    studytime += +e.studytime||0;
                })
                studyform.value.alltime = alltime;
                studyform.value.studytime = studytime;
            }
            isupdata.value = true
            isEdit.value = 3
            speed.value = studyform.value.study[tabidx.value].isstudy
            // 附件处理
            detail.value.filejson = typeof detail.value.filejson =='object'?detail.value.filejson:[]
        }
    }

    const sign = (id)=>{
        if(id){
            proxy.$ajax({url: 'train/sign',data:{train_id:id},bfLoading: true}).then(d => {
                console.log(d);
                if(d.success){
                    proxy.elMessageMixin('成功！', 'success')
                    detail.value.complete = detail.value.complete==''?'0':''
                    detail.value.verify_state = detail.value.verify_state==''?'0':''
                    updalist()
                }else{proxy.elMessageMixin(date.err, 'error')}
            }).catch(e => {
                console.log(e)
                if(e == "登录已过期，请重新登录"){
                    proxy.routerPushMixin('/')
                }
            })
        }
    }

    //更新学习情况
    const updatastudy = (param)=>{
        isupdata.value = true
        proxy.$ajax({url: 'train/study',data:param,bfLoading: false}).then(d => {
            console.log(d);
            if(d.success){
                // proxy.elMessageMixin('学习记录成功！', 'success')
                //完成该课程
                let complete = true
                studyform.value.study.map(e=>{
                    if(complete&&e.studytime<e.alltime||(e.studytime==0&&e.alltime==0)){
                        complete = false
                    }
                })
                if(complete){
                    completestudy(studyform.value.train_id)
                } 
            }else{proxy.elMessageMixin(date.err, 'error')}
        }).catch(e => {
            console.log(e)
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }

    //完成学习train/complete
    const completestudy = (id)=>{
        proxy.$ajax({url: 'train/complete',data:{train_id:id},bfLoading: true}).then(d => {
            console.log(d);
            if(d.success){
                detail.value.complete = 1
                proxy.elMessageMixin('该课程已完成学习！', 'success')
            }else{proxy.elMessageMixin(date.err, 'error')}
        }).catch(e => {
            console.log(e)
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }

    const playvideo = ()=>{
        // console.log('播放了');
        // speed.value = studyform.value.study[tabidx.value].isstudy
        // videokey.value = (Math.random() * 100000).toFixed(0)
        // console.log(speed.value);
    }

    const onTimeupdate = (ev) => {
        if(studyform.value.study[tabidx.value].isstudy){
            return
        }
        // console.log(ev.srcElement);
        if(ev.srcElement.duration!==ev.srcElement.duration){
            // proxy.elMessageMixin('视频格式错误', 'error')
            return
        }
        if(detail.value.complete==1){
            return
        }
        let alltime = +ev.srcElement.duration
        let studytime = +ev.srcElement.currentTime.toFixed(0)
        if(studytime&&studytime%5==0&&isupdata.value){
            console.log(studytime);
            isupdata.value = false
            studyform.value.study[tabidx.value].studytime = studytime
            studyform.value.study[tabidx.value].alltime = alltime

            //该视频学习完成
            if(alltime-5<=studytime){
                studyform.value.study[tabidx.value].studytime = alltime
                studyform.value.study[tabidx.value].isstudy = true
            }
            // return
            //更新学习情况
            proxy.$utils.debounce(updatastudy,studyform.value,1000)
        }
    };

    const loadedmetadata = (ev) => {
        console.log(ev);
    };

    const chart = ()=>{
        proxy.routerPushNewMixin('/chartmechanismdetail',{
            id: detail.value.train_id,
            name: detail.value.name,
            mechanism_id: detail.value.mechanism_id,
            mechanism_name: detail.value.mechanism_name,
            type: 'train'
        })
    }
    
    
    let { list, sifterForm, isEdit, total, fileurl, detail, tabidx, videoOptions, speed, videokey, studyform, isupdata } = toRefs(obj)
</script>

<style lang="scss" scoped>
    .video-box{
        width: 896px;height: auto;position:relative;
        .videos-tab{
            width: 160px;height: 415px;overflow-y: auto; background: #f7f7f7;
            .tab{background: #f0f0f0;border-radius: 0px;}
            .tab-active{background: rgba(0,122,255,0.1);color: rgba(0,122,255,1);}
            .mulu-success{background: rgba(66,207,149,0.1);color: rgba(66,207,149,1);}
        }
        .sign-box{
            position: absolute;left: 0;top: 0;right: 0;bottom: 0;background: rgba(0,0,0,0.6);
            .sign{
                width: 160px;height: 50px;border-radius: 0px;color: #fff;background: #1f71e0;
            }
        }
    }
    .head-box{width: 100%;
        .cancel{
            width: 160px;height: 50px;border-radius: 0px;
        }
    }
</style>